//
//  SendViewController.m
//  HCWeibo
//
//  Created by gj on 15/12/18.
//  Copyright © 2015年 www.iphonetrain.com 无限互联. All rights reserved.
//

#import "SendViewController.h"
#import "ThemeButton.h"
#import "MMDrawerController.h"
#import "NetworkService.h"
#import "ZoomImageView.h"


@interface SendViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, ZoomImageViewDelegate>

@end

@implementation SendViewController{
    //1 文本编辑栏
    UITextView *_textView;
    //2 工具栏
    UIView *_editorBar;

    ZoomImageView *imageView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //监听键盘弹出通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];

    [self _createNavItems];
    [self _createEditorViews];
    if (imageView == nil) {
        imageView = [[ZoomImageView alloc] initWithFrame:CGRectMake(CGRectGetMinX(_textView.frame), CGRectGetMaxY(_textView.frame), 80, 80)];
        [self.view addSubview:imageView];
        imageView.delegate = self;
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    //导航栏不透明
    self.navigationController.navigationBar.translucent = NO;
    _textView.frame = CGRectMake(0, 0, kScreenWidth, 120);
    //内容偏移
  // _textView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    //弹出键盘
    [_textView becomeFirstResponder];
    
    
}


#pragma  mark - 创建子视图
- (void)_createNavItems{
    //1.关闭按钮
    ThemeButton *closeButton = [[ThemeButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    closeButton.normalImageName = @"button_icon_close.png";
    [closeButton addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithCustomView:closeButton];
    [self.navigationItem setLeftBarButtonItem:closeItem];
    
    //2.发送按钮
    ThemeButton *sendButton = [[ThemeButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    sendButton.normalImageName = @"button_icon_ok.png";
    [sendButton addTarget:self action:@selector(sendAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *sendItem = [[UIBarButtonItem alloc] initWithCustomView:sendButton];
    [self.navigationItem setRightBarButtonItem:sendItem];
    
}

- (void)_createEditorViews{
    
    //1 文本输入视图
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 120)];
    _textView.font = [UIFont systemFontOfSize:16.0f];
  
    _textView.editable = YES;
    
    _textView.backgroundColor = [UIColor lightGrayColor];
    _textView.layer.cornerRadius = 10;
    _textView.layer.borderWidth = 2;
    _textView.layer.borderColor = [UIColor blackColor].CGColor;
    
    [self.view addSubview:_textView];
    //2 编辑工具栏
    _editorBar = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, 55)];
    _editorBar.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_editorBar];
    //3.创建多个编辑按钮
    NSArray *imgs = @[
                      @"compose_toolbar_1.png",
                      @"compose_toolbar_4.png",
                      @"compose_toolbar_3.png",
                      @"compose_toolbar_5.png",
                      @"compose_toolbar_6.png"
                      ];
    for (int i=0; i<imgs.count; i++) {
        NSString *imgName = imgs[i];
        ThemeButton *button = [[ThemeButton alloc] initWithFrame:CGRectMake(15+(kScreenWidth/5)*i, 20, 40, 33)];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 10+i;
        button.normalImageName = imgName;
        [_editorBar addSubview:button];
    }
    
  
}

//发送微博
- (void)sendAction{
    NSString *text = _textView.text;
    NSString *error = nil;
    if (text.length == 0) {
        error = @"微博内容为空";
    }
    else if(text.length > 140) {
        error = @"微博内容大于140字符";
    }
    if (error != nil) {

        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:error preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSLog(@"HELLO");
            
        }];
        [alert addAction:action];
        
        
        [self presentViewController:alert animated:YES completion:nil];
        
        
        return;
    }
    
    [NetworkService sendWeibo:text image:imageView.image block:^(id result, NSURLResponse *response, NSError *error) {
    
    }];
    
    

    [self closeAction];
    
}


//关闭窗口
- (void)closeAction{
    //通过UIWindow找到  MMDRawer
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    if ([window.rootViewController isKindOfClass:[MMDrawerController class]]) {
        MMDrawerController *mmDrawer = (MMDrawerController *)window.rootViewController;
        
        [mmDrawer closeDrawerAnimated:YES completion:NULL];
    }
    [_textView resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:NULL];
    
}

- (void)buttonAction:(UIButton*)button{
    NSLog(@"%li",button.tag);
    
    
    if (button.tag == 10) { //选择照片
        
        [self sourceSelector];

    }else if(button.tag == 14) {  //显示、隐藏表情
        
      
        
    }
    
}

- (void)sourceSelector
{
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"Tip" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *album = [UIAlertAction actionWithTitle:@"Album" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       
        [self pickImage:NO];
    }];
    
    UIAlertAction *photo = [UIAlertAction actionWithTitle:@"Camare" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self pickImage:YES];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    [actionSheet addAction:album];
    [actionSheet addAction:photo];
    [actionSheet addAction:cancel];
    
    [self presentViewController:actionSheet animated:YES completion:nil];
    
}

- (void)pickImage:(BOOL)isCamare
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    if (isCamare) {
        
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
            
            UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"Warning" message:@"NO Camare" preferredStyle:UIAlertControllerStyleAlert];
            
            [self presentViewController:alter animated:YES completion:^{
                [self performSelector:@selector(cancel) withObject:nil afterDelay:1];
            }];
        }
    }else{
        
        picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        
    }
    
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:^{
        
    }];
    
}

- (void)cancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    imageView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 键盘弹出通知

- (void)keyBoardWillShow:(NSNotification *)notification{
    
    NSLog(@"%@",notification);
    //1 取出键盘frame
    NSValue *bounsValue = [notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    CGRect frame = [bounsValue CGRectValue];
    //2 键盘高度
    
    //3 调整视图的高度
    _editorBar.bottom = frame.origin.y - 64;
    
}

#pragma mark - ZoomImageViewDelegate

- (void)imageViewDidZoomIn:(ZoomImageView *)imageView
{
    [_textView resignFirstResponder];
}

- (void)imageViewDidZoomOut:(ZoomImageView *)imageView
{
    [_textView becomeFirstResponder];
}



@end
